package com.baijiayun.live.ui.toolbox.questionanswer

import androidx.lifecycle.Observer
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Paint.FontMetricsInt
import android.os.Bundle
import androidx.core.content.ContextCompat
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.baijiayun.live.ui.DatabindingUtils
import com.baijiayun.live.ui.R
import com.baijiayun.live.ui.base.BaseDialogFragment
import com.baijiayun.live.ui.base.BasePadFragment
import com.baijiayun.live.ui.base.getViewModel
import com.baijiayun.live.ui.isAdmin
import com.baijiayun.livecore.context.LPError
import com.baijiayun.livecore.models.LPQuestionPullListItem
import com.baijiayun.livecore.models.LPQuestionPullResItem
import com.baijiayun.livecore.utils.CommonUtils
import com.baijiayun.liveuibase.utils.DisplayUtils
import com.baijiayun.liveuibase.utils.LinearLayoutWrapManager
import com.baijiayun.liveuibase.utils.ThemeDataUtil
import com.baijiayun.liveuibase.utils.drawable.DrawableBuilder
import com.baijiayun.liveuibase.widgets.chat.TextLineHeightSpan
import kotlinx.android.synthetic.main.fragment_qa_detail.*
import kotlin.math.roundToInt


/**
 * Created by yongjiaming on 2019-10-30
 * Describe: 单种问答状态展示页面
 */
enum class QuestionStatus(val status: Int) {
    QuestionPublished(1 shl 0),     //1  已发布
    QuestionUnPublished(1 shl 1),   //2  未发布
    QuestionReplied(1 shl 2),       //4  已回复
    QuestionUnReplied(1 shl 3),     //8  未回复
    QuesitonAllState((1 shl 4) - 1) //15 全部
}

class QADetailFragment : BasePadFragment() {
    private var tabStatus: QATabStatus = QATabStatus.Published
    private lateinit var recyclerView: androidx.recyclerview.widget.RecyclerView
    private lateinit var adapter: QAAdapter
    private lateinit var qaViewModel: QAViewModel
    private lateinit var emptyView: View
    private lateinit var questionSendFragment: BaseDialogFragment

    private val clipboardManager: ClipboardManager? by lazy {
        activity?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    }

    private val navigateToMainObserver by lazy {
        Observer<Boolean> {
            if (it == true) {
                initSuccess()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        tabStatus = arguments?.get("status") as QATabStatus
    }

    override fun init(view: View) {
        qaViewModel = getViewModel { QAViewModel(routerViewModel) }
        recyclerView = view.findViewById(R.id.qa_recyclerview)
        recyclerView.layoutManager = LinearLayoutWrapManager(context)
        adapter = QAAdapter()
        recyclerView.adapter = adapter
        emptyView = view.findViewById(R.id.qa_empty_container)
        if (isAdmin(routerViewModel.liveRoom)) {
            qa_empty_tv.text = getString(R.string.live_qa_empty_teacher)
        } else {
            if (tabStatus == QATabStatus.Published) {
                qa_empty_tv.text = getString(R.string.live_qa_published_empty_student)
            } else {
                qa_empty_tv.text = getString(R.string.live_my_qa_empty_student)
            }
        }
    }

    private fun initSuccess() {
        qaViewModel.tabStatus = tabStatus
        qaViewModel.subscribe()
        qaViewModel.questionList.observe(this, Observer {
            it?.let {
                refreshLayout.isRefreshing = false
                emptyView.visibility = if (it.isEmpty()) View.VISIBLE else View.GONE
                adapter.notifyDataSetChanged()
                if (adapter.itemCount >= 1) {
                    if (qaViewModel.needScroll) {
                        recyclerView.post {
                            val position = adapter.itemCount - 1
                            recyclerView.smoothScrollToPosition(position)
                        }
                    } else{
                        val linearLayoutManager = recyclerView.layoutManager as LinearLayoutWrapManager
                        val lastVisiablePosition = linearLayoutManager.findLastVisibleItemPosition()
                        //学生收到新的问答提示，且最下面可见不是最后一个item则提示学生
                        if (qaViewModel.showNewReminder && !isAdmin(routerViewModel.liveRoom) && lastVisiablePosition < linearLayoutManager.itemCount - 1) {
                            qa_new_reminder_container.visibility = View.VISIBLE
                        }
                    }
                }
            }
        })
        qa_new_reminder_container.setOnClickListener {
            if (adapter.itemCount >= 1) {
                recyclerView.smoothScrollToPosition(adapter.itemCount - 1)
            }
        }
        qa_new_reminder_container.background = DrawableBuilder()
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color))
                .cornerRadius(context!!.resources!!.getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .build()
        qaViewModel.notifyLoadEmpty.observe(this, Observer {
            it?.let {
                refreshLayout.isRefreshing = false
            }
        })
        routerViewModel.action2SaveQuestion.observe(this, Observer {
            it?.let {
                if (tabStatus == it.first) {
                    val map = it.second
                    if (map.isNotEmpty()) {
                        val id = map["id"]
                        val content = map["content"]
                        if (!id.isNullOrEmpty() && !content.isNullOrEmpty()) {
                            qaViewModel.saveQuestion(id,content)
                        }
                    }
                }
            }
        })
        refreshLayout.setOnRefreshListener {
            val error = loadData()
            if (error != null) {
                refreshLayout.isRefreshing = false
            }
        }
        loadData()
    }

    private fun loadData(): LPError? {
        //学生只有我的问答和已发布
        return if (isAdmin(routerViewModel.liveRoom)) {
            val status = when (tabStatus) {
                QATabStatus.ToAnswer -> 8
                QATabStatus.ToPublish -> 6
                QATabStatus.Published -> 1
                else -> 15
            }
            qaViewModel.loadMoreQuestions(status, false)
        } else {
            //toAnswer在学生中是我的问题
            val status = if (tabStatus == QATabStatus.AllStatus) 15 else 1
            qaViewModel.loadMoreQuestions(status, tabStatus == QATabStatus.AllStatus)
        }
    }

    override fun observeActions() {
        routerViewModel.actionNavigateToMain.observeForever(navigateToMainObserver)
    }

    override fun getLayoutId() = R.layout.fragment_qa_detail

    inner class QAAdapter : androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
            val view = LayoutInflater.from(context).inflate(R.layout.item_pad_qa, parent, false)
            return QAItemViewHolder(view)
        }

        override fun onBindViewHolder(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
            if (viewHolder is QAItemViewHolder) {
                if (position == itemCount - 1) {
                    qa_new_reminder_container.visibility = View.GONE
                }
                qaViewModel.questionList.value?.let {
                    val questionPullResItem: LPQuestionPullResItem = it[position]
                    if (!questionPullResItem.itemList.isNullOrEmpty()) {
                        val userModel = questionPullResItem.itemList[0].from
                        viewHolder.nameTv.text = CommonUtils.getEncodePhoneNumber(userModel.name)
                        viewHolder.timeTv.text = DatabindingUtils.formatTime(questionPullResItem.itemList[0].time * 1000)
                        if (!isAdmin(routerViewModel.liveRoom) && routerViewModel.liveRoom.currentUser.number == userModel.number && tabStatus == QATabStatus.Published) {
                            viewHolder.meTv.visibility = View.VISIBLE
                        } else {
                            viewHolder.meTv.visibility = View.GONE
                        }
                        viewHolder.qaContainer.removeAllViews()
                        for (i in questionPullResItem.itemList.indices) {
                            val item = questionPullResItem.itemList[i]
                            if (i == 0) {
                                buildQuestionView(questionPullResItem.id, questionPullResItem.status, viewHolder.qaContainer, item)
                            } else {
                                buildAnswerView(questionPullResItem.id, viewHolder.qaContainer, item, questionPullResItem.status)
                            }
                        }
                    }
                }
            }
        }

        override fun getItemCount() = qaViewModel.questionList.value?.size ?: 0
    }

    private fun buildQuestionView(questionId: String, status: Int, container: ViewGroup, item: LPQuestionPullListItem) {
        val ctx = container.context
        val spannableString = SpannableString("image${item.content}")
        val imageSpan = CenterAlignImageSpan(ctx, R.drawable.ic_pad_qa_question)
        spannableString.setSpan(imageSpan, 0, 5, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        val textView = TextView(ctx)
        val fontMetricsInt: FontMetricsInt = textView.paint.fontMetricsInt
        val lineHeightSpan = TextLineHeightSpan(fontMetricsInt, 8)
        spannableString.setSpan(lineHeightSpan, 0, spannableString.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        textView.text = spannableString
        textView.gravity = Gravity.CENTER_VERTICAL
        textView.setTextColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(ctx, R.attr.base_theme_window_main_text_color))
        val params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        params.leftMargin = resources.getDimensionPixelSize(R.dimen.qa_item_padding)
        params.rightMargin = resources.getDimensionPixelSize(R.dimen.qa_item_padding)
        container.addView(textView, params)
        if (isAdmin(routerViewModel.liveRoom)) {
            textView.setOnClickListener {
                showPopupWindow(textView, container.width, questionId, status, item)
            }
        }
    }

    private fun buildAnswerView(questionId: String, container: ViewGroup, item: LPQuestionPullListItem, status: Int) {
        val ctx = container.context
        val spannableString = SpannableString("image${item.content}")
        val drawableId = R.drawable.ic_pad_qa_answer
        val imageSpan = CenterAlignImageSpan(ctx, drawableId)
        spannableString.setSpan(imageSpan, 0, 5, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        val textView = TextView(ctx)
        val fontMetricsInt: FontMetricsInt = textView.paint.fontMetricsInt
        val lineHeightSpan = TextLineHeightSpan(fontMetricsInt, 8)
        spannableString.setSpan(lineHeightSpan, 0, spannableString.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        textView.text = spannableString
        textView.gravity = Gravity.CENTER_VERTICAL
        textView.setTextColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(ctx, R.attr.base_theme_window_main_text_color))
        val relativeLayout = RelativeLayout(context)
        val timeText = TextView(context)
        timeText.setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.common_text_size))
        timeText.setTextColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(ctx, R.attr.base_theme_window_assistant_text_color))
        val timeParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
        timeParams.addRule(RelativeLayout.ALIGN_PARENT_END)
        timeText.text = DatabindingUtils.formatTime(item.time * 1000)
        val nameText = TextView(context)
        nameText.setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.common_text_size))
        nameText.setTextColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(ctx, R.attr.base_theme_window_main_text_color))
        nameText.text = item.from.name
        nameText.setSingleLine()
        nameText.ellipsize = TextUtils.TruncateAt.END
        val nameParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
        nameParams.addRule(RelativeLayout.START_OF, timeText.id)
        relativeLayout.addView(timeText, timeParams)
        relativeLayout.addView(nameText, nameParams)
        val div = View(context)
        div.setBackgroundColor(ContextCompat.getColor(ctx, R.color.base_divider_line_other))
        val divParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, DisplayUtils.dip2px(ctx, 1f))
        divParams.topMargin = DisplayUtils.dip2px(ctx, 2f)
        divParams.bottomMargin = DisplayUtils.dip2px(ctx, 2f)
        val params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        params.leftMargin = resources.getDimensionPixelSize(R.dimen.qa_item_padding)
        params.rightMargin = resources.getDimensionPixelSize(R.dimen.qa_item_padding)
        container.addView(div, divParams)
        container.addView(relativeLayout, params)
        container.addView(textView, params)
        if (routerViewModel.liveRoom.isTeacherOrAssistant || routerViewModel.liveRoom.isGroupTeacherOrAssistant) {
            textView.setOnClickListener {
                showPopupWindow(textView, container.width, questionId, status, item)
            }
        }
    }

    private fun buildPopupWindowTipArray(status: Int, ctx: Context): Array<String> {
        val apply: String = if ((status and QuestionStatus.QuestionUnReplied.status) > 0) ctx.resources.getString(R.string.qa_replay) else ctx.resources.getString(R.string.qa_append_apply)
        val publish: String = if ((status and QuestionStatus.QuestionPublished.status) > 0) ctx.resources.getString(R.string.qa_cancel_publish) else ctx.resources.getString(R.string.qa_publish)
        val copy: String = ctx.resources.getString(R.string.qa_copy_question)
        return arrayOf(apply, publish, copy)
    }

    private fun showPopupWindow(anchorView: View, containerWidth: Int, questionId: String, status: Int, item: LPQuestionPullListItem) {
        val popupWindow = ListPopupWindow(anchorView.context)
        popupWindow.setBackgroundDrawable(ThemeDataUtil.getCommonWindowBg(context))
        with(popupWindow) {
            this.anchorView = anchorView
            // 弹出框4：3
            width = anchorView.context.resources.getDimension(R.dimen.qa_item_popup_window_width).roundToInt()
            height = width / 3 * 4
            setDropDownGravity(Gravity.START)
            horizontalOffset = (containerWidth - width) / 2
            setAdapter(ArrayAdapter(anchorView.context, R.layout.item_pad_qa_menu, buildPopupWindowTipArray(status, anchorView.context)))
            setOnItemClickListener { _, _, position, _ ->
//                val quoteContent = if ((status and QuestionStatus.QuestionReplied.status) > 0) {
//                    "${CommonUtils.getEncodePhoneNumber(item.from.user.name)} : ${item.content}"
//                } else {
//                    ""
//                }
                val quoteContent = "${CommonUtils.getEncodePhoneNumber(item.from.user.name)} : ${item.content}"
                questionSendFragment = QuestionSendFragment.newInstance(questionId, quoteContent, tabStatus)
                if (questionSendFragment.isAdded) {
                    return@setOnItemClickListener
                }
                when (position) {
                    //回复or追加回复
                    0 -> {
                        showDialogFragment(questionSendFragment)
                    }
                    //发布or取消发布
                    1 -> {
                        if ((status and QuestionStatus.QuestionPublished.status) > 0) {
                            qaViewModel.unPublishQuestion(questionId, item.content)
                        } else {
                            qaViewModel.publishQuestion(questionId, item.content)
                        }
                    }
                    //复制
                    2 -> {
                        copyQuestion(item)
                    }
                }
                dismiss()
            }
            show()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        routerViewModel.actionNavigateToMain.removeObserver(navigateToMainObserver)
    }

    class QAItemViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
        val nameTv: TextView = itemView.findViewById(R.id.qa_ask_from_name)
        val timeTv: TextView = itemView.findViewById(R.id.qa_ask_time)
        val meTv: TextView = itemView.findViewById(R.id.qa_ask_from_me)
        val qaContainer: LinearLayout = itemView.findViewById(R.id.qa_content_container)
    }

    private fun copyQuestion(item: LPQuestionPullListItem) {
        val content = "${CommonUtils.getEncodePhoneNumber(item.from.user.name)} 提问: ${item.content}"
        val clipData = ClipData.newPlainText("Label", content)
        clipboardManager?.setPrimaryClip(clipData)
    }

    companion object {
        fun newInstance(tabStatus: QATabStatus): QADetailFragment {
            val fragment = QADetailFragment()
            val bundle = Bundle()
            bundle.putSerializable("status", tabStatus)
            fragment.arguments = bundle
            return fragment
        }
    }

    enum class QATabStatus {
        ToAnswer, ToPublish, Published, AllStatus
    }
}